//
//  LBDownLoadManager.m
//  FBSnapshotTestCase
//
//  Created by liubo on 2021/12/18.
//

#import "LBDownLoadManager.h"
#import "NSString+MD5.h"

@interface LBDownLoadManager()

@property (nonatomic, strong) NSMutableDictionary  *downLoaderInfo;

@end

@implementation LBDownLoadManager

-(NSMutableDictionary *)downLoaderInfo {
    if (!_downLoaderInfo) {
        _downLoaderInfo = [NSMutableDictionary dictionary];
    }
    return _downLoaderInfo;
}
- (void)downLoader:(NSURL*)url
      downLoadInfo:(DownLoadInfoBlock)downLoadInfo
          progress:(ProgressBlock)progressBlock
           success:(SuccessBlock)successBlock
            failed:(FailedBlock)failedBlock {

    // 1. url
    NSString *urlMD5 = [url.absoluteString md5];
    // 2.根据urlMD5,查找相应的下载器
    LBDownLoader *downLoader =self.downLoaderInfo[urlMD5];
    if (downLoader == nil) {
        downLoader = [[LBDownLoader alloc]init];
        self.downLoaderInfo[urlMD5] = downLoader;
    }
    // 下载完成之后，移除下载器
    downLoader.fileName = self.fileName;
    [downLoader downLoader:url downLoadInfo:downLoadInfo progress:progressBlock success:^(NSString *filePath) {
        //拦截block
        [self.downLoaderInfo removeObjectForKey:urlMD5];
        successBlock(filePath);
    } failed:failedBlock];
}

- (void)downLoader:(NSURL*)url
      downloadPath:(NSString *)downLoadPath
          tempPath:(NSString *)tempPath
      downLoadInfo:(DownLoadInfoBlock)downLoadInfo
          progress:(ProgressBlock)progressBlock
           success:(SuccessBlock)successBlock
            failed:(FailedBlock)failedBlock
{
    // 1. url
    NSString *urlMD5 = [url.absoluteString md5];
    // 2.根据urlMD5,查找相应的下载器
    LBDownLoader *downLoader =self.downLoaderInfo[urlMD5];
    if (downLoader == nil) {
        downLoader = [[LBDownLoader alloc]init];
        self.downLoaderInfo[urlMD5] = downLoader;
    }
    downLoader.fileName = self.fileName;
    [downLoader downLoader:url downloadPath:downLoadPath tempPath:tempPath downLoadInfo:downLoadInfo progress:progressBlock success:^(NSString *filePath) {
        [self.downLoaderInfo removeObjectForKey:urlMD5];
        successBlock(filePath);
    } failed:failedBlock];
}

- (void)pauseWithURL:(NSURL *)url {
    NSString *urlMD5 = [url.absoluteString md5];
    LBDownLoader *downLoader =self.downLoaderInfo[urlMD5];
    [downLoader pauseCurrentTask];
}

- (void)resumeWithURL:(NSURL *)url {
    NSString *urlMD5 = [url.absoluteString md5];
    LBDownLoader *downLoader =self.downLoaderInfo[urlMD5];
    [downLoader resumeCurrentTask];
}

- (void)cancleWithURL:(NSURL *)url {
    NSString *urlMD5 = [url.absoluteString md5];
    LBDownLoader *downLoader =self.downLoaderInfo[urlMD5];
    [downLoader cancleCurrentTask];
}

// 暂停所有
- (void)pauseAll {
    [self.downLoaderInfo.allValues performSelector:@selector(pauseCurrentTask) withObject:nil];
}
// 恢复所有
- (void)resumeAll {
    [self.downLoaderInfo.allValues performSelector:@selector(resumeCurrentTask) withObject:nil];
}


@end
